<?php
/**
 * Created by PhpStorm.
 * User: Hk
 * Date: 2021/1/26
 * Time: 18:11
 */

namespace App\Models;

use Mockery\Exception;

class Community extends Base
{
    // 数据表主键
    protected $primaryKey = 'community_id';
    public $timestamps = false;
    //protected $connection = 'mysql_center';
    protected $table = 'community';

    public function getCreateTimeAttribute($value)
    {
        return $value;
    }

    public function getPaginate($where = null, $order = 'id', $sort = 'desc', $field = null, $limit = 15)
    {
        $model = self::where($where);
        if (isset($order)) {
            $model = $model->orderBy($order, $sort);
        }

        if (isset($limit)) {
            $model = $model->limit($limit);
        }

        if(isset($field)){
            $field = explode(',',$field);
            return $model  -> toArray();
        }

        return Community::query() -> paginate($limit) -> toArray();
        if (isset($field)) {
            $field = explode(',', $field);
            return $model->toArray();
        }
//        ->join('electric_platform_agent_copy', 'electric_platform_agent_copy.id ', '=', 'electric_community.agent_id')->
//        join('electric_platform_agent_copy','electric_platform_agent_copy.id ','=','electric_community.agent_id')->
        return Community::query()->select()->paginate($limit)->toArray();
    }

    /**
     * Notes: 关联楼栋
     * User: lstink
     * Date: 2021/2/4
     * Time: 11:06 上午
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function house()
    {
        return $this->hasMany(HouseModel::class, 'c_id');
    }

    // 添加
    public function create($data)
    {
        [$data['province'], $data['city'], $data['area']] = $data['areas'];
        $data['create_time'] = time();
        unset($data['areas']);
        return self::addInfo($data);
    }

    // 修改
    public function edit($data)
    {
        [$data['province'], $data['city'], $data['area']] = $data['areas'];
        unset($data['areas']);
        unset($data['status']);
        unset($data['create_time']);
        return self::updateByWhere(['community_id' => $data['community_id']], $data);
    }

    // 删除
    public function deletes($ids)
    {
        $ids = explode(',', $ids);
        try {
            foreach ($ids as $key => $val) {
                self::delByWhere(['community_id' => $val]);
            }
            return true;
        } catch (Exception $exception) {
            return false;
        }
    }

    /**
     * 获取小区绑定的物业id
     * @param $community_id
     * @return mixed
     * @author ypp
     * @date 2021/003/03
     */
    public static function getPropertId($community_id)
    {
        return self::where('community_id', $community_id)->value('property_id');
    }

}
